package servlet;

import java.io.IOException;
import java.io.Writer;
import java.sql.SQLException;
import java.util.ArrayList;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import model.Employee;

import org.json.JSONArray;
import org.json.JSONObject;

import dao.EmployeeDAO;
import dao.ProfileDAO;

/**
 * Servlet implementation class employeeData
 */
public class employeeData extends HttpServlet {
	private static final long serialVersionUID = 1L;
	EmployeeDAO emDao;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public employeeData() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		
		Writer out = response.getWriter();
		String jsonString = "";
		
		/**
		 * cast data from database into json to present on Jqgrid in view
		 */
		
		try {
			emDao = new EmployeeDAO();
			
			ArrayList<Employee> list = emDao.getListEmployees();
			if(!list.isEmpty()) {				
				JSONArray cellArray = new JSONArray();
				for(Employee em : list) {
					JSONObject cellObj = new JSONObject();
					String temp = em.getFullname() + " (" + em.getUsername() + ")";
					cellObj.put("label", temp);
					cellObj.put("value", em.getUserid());
					
					cellArray.put(cellObj);
				}
				
				jsonString = cellArray.toString();
			}

			out.write(jsonString);
			out.flush();		
			
		} catch (SQLException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

}
